﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace WindowsFormsApplication3
{
    public class AppConfigProcess
    {
        #region 设置App.Config文件key名对应的key值 【SetConfigValue(string AppKey,string AppValue)】

        /// <summary>
        /// 设置当前程序集的配置文件
        /// </summary>
        /// <param name="AppKey"></param>
        /// <param name="AppValue"></param>
        public static void SetConfigValue(string AppKey, string AppValue)
        {
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");      //加载配置config文件

            XmlNode    xNode;
            XmlElement xElem1;
            XmlElement xElem2;

            xNode = xDoc.SelectSingleNode("//appSettings");

            xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");  //key名称查找
            /*
            举例:
            <add key="BTL2" value="2400">
            </add>
            */
            if (xElem1 != null)
            {
                xElem1.SetAttribute("value", AppValue);  //修改key值
            }
            else
            {
                xElem2 = xDoc.CreateElement("add");
                xElem2.SetAttribute("key", AppKey);      //设置key名称
                xElem2.SetAttribute("value", AppValue);  //设置key值
                xNode.AppendChild(xElem2);               //添加xElem
            }
            xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");   //保存配置config文件
        }

        #endregion

        #region 获取当前配置文件的信息key名对应的key值【 GetConfigXml(string strKey)】
        /// <summary>
        /// 获取当前配置文件的信息
        /// </summary>
        /// <param name="strKey">键</param>
        /// <returns></returns>
        public static string GetConfigXml(string strKey)
        {
            string strReValue = ""; //返回值
            try
            {
                string strConfigName = System.Windows.Forms.Application.ExecutablePath + ".config"; //获取应用程序配置文件名称
                XmlDocument xmlConfig = new XmlDocument();
                xmlConfig.Load(strConfigName);                                                      //加载配置文件
                XmlNode xmlNode = xmlConfig.DocumentElement.SelectSingleNode("appSettings");
                /*
                举例:
                <add key="BTL2" value="2400">
                </add>
                */
                strReValue = xmlNode.SelectSingleNode("descendant::add[@key='" + strKey + "']").Attributes[1].Value;
            }
            catch
            {

            }

            return strReValue;
        }

        #endregion
    }


}
